<template>
  <div class="quality-config flex h-full">
    <!-- 左侧数据目录树 -->
    <div class="w-64 bg-white p-4 border-r">
      <div class="text-lg font-medium mb-4">数据目录</div>
      <el-input
        v-model="searchText"
        placeholder="搜索..."
        prefix-icon="i-carbon-search"
        clearable
        class="mb-4"
      />
      <el-tree
        ref="treeRef"
        :data="treeData"
        :props="defaultProps"
        node-key="id"
        highlight-current
        @node-click="handleNodeClick"
      />
    </div>

    <!-- 右侧内容区 -->
    <div class="flex-1 p-4">
      <!-- 搜索和操作按钮 -->
      <div class="flex justify-between items-center mb-4">
        <div class="flex items-center gap-4">
          <el-select v-model="selectedTemplate" placeholder="规则模板" class="w-60">
            <el-option label="检测不唯一" value="检测不唯一" />
            <el-option label="检测手机号不正确" value="检测手机号不正确" />
          </el-select>
          <el-button type="primary" @click="handleSearch">
            <div class="i-carbon-search mr-1" />
            查询
          </el-button>
        </div>
        <div class="flex gap-2">
          <el-button type="primary" @click="handleAdd">
            <div class="i-carbon-add mr-1" />
            添加
          </el-button>
          <el-button type="danger" :disabled="!selectedRows.length" @click="handleBatchDelete">
            <div class="i-carbon-trash-can mr-1" />
            删除
          </el-button>
        </div>
      </div>

      <!-- 规则列表 -->
      <div class="bg-white p-6 rounded-lg shadow-md">
        <ArtTable 
          :data="ruleList" 
          :loading="loading"
          stripe
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column type="index" label="序号" width="80" align="center" />
          <el-table-column prop="checkObject" label="检测对象" min-width="120" show-overflow-tooltip />
          <el-table-column prop="checkField" label="检测字段" min-width="120" show-overflow-tooltip />
          <el-table-column prop="checkRule" label="检测规则" min-width="200" show-overflow-tooltip />
          <el-table-column label="操作" width="200" fixed="right">
            <template #default="scope">
              <el-button type="primary" link @click="handleEdit(scope.row)">
                <div class="i-carbon-edit mr-1" />
                编辑
              </el-button>
              <el-button type="danger" link @click="handleDelete(scope.row)">
                <div class="i-carbon-trash-can mr-1" />
                删除
              </el-button>
              <el-button type="warning" link @click="handleDebug(scope.row)">
                <div class="i-carbon-debug mr-1" />
                调试
              </el-button>
            </template>
          </el-table-column>
        </ArtTable>

        <!-- 分页 -->
        <div class="flex justify-end mt-4">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :total="total"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </div>

    <!-- 添加/编辑规则对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '添加检测规则' : '编辑检测规则'"
      width="600px"
      destroy-on-close
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="100px"
        label-position="right"
      >
        <el-form-item label="规则模板" prop="ruleTemplate">
          <el-select v-model="formData.ruleTemplate" placeholder="请选择" class="w-full">
            <el-option label="检测不唯一" value="检测不唯一" />
            <el-option label="检测手机号不正确" value="检测手机号不正确" />
          </el-select>
        </el-form-item>
        <el-form-item label="检测数据范围" prop="checkRange">
          <el-input
            v-model="formData.checkRange"
            type="textarea"
            :rows="4"
            placeholder="请输入检测数据范围"
          />
        </el-form-item>
        <el-form-item label="检测字段" prop="checkFields">
          <el-table :data="formData.checkFields" border class="w-full">
            <el-table-column type="selection" width="55" />
            <el-table-column prop="id" label="ID" width="80" />
            <el-table-column prop="fieldName" label="检测字段名" />
            <el-table-column prop="fieldDesc" label="检测字段中文名" />
            <el-table-column prop="description" label="说明" />
          </el-table>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 调试对话框 -->
    <el-dialog
      v-model="debugDialogVisible"
      title="调试规则"
      width="800px"
    >
      <div class="mb-4">
        <div class="font-medium mb-2">规则内容:</div>
        <el-input
          v-model="debugRule"
          type="textarea"
          :rows="4"
          readonly
        />
      </div>
      <div class="mb-4">
        <div class="font-medium mb-2">调试结果:</div>
        <div class="bg-gray-50 p-4 rounded">
          <pre>{{ debugResult }}</pre>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="debugDialogVisible = false">关闭</el-button>
          <el-button type="primary" @click="runDebug">执行调试</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { ElMessage } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'

// 左侧树相关
const searchText = ref('')
const treeRef = ref()
const treeData = ref([
  {
    id: 1,
    label: '数据中心',
    children: [
      {
        id: 11,
        label: '学校概况数据子集',
        children: [
          {
            id: 111,
            label: '学校基本数据子集'
          }
        ]
      },
      {
        id: 12,
        label: '学生管理数据子集'
      }
    ]
  }
])

const defaultProps = {
  children: 'children',
  label: 'label'
}

// 表格数据
const loading = ref(false)
const selectedTemplate = ref('')
const ruleList = ref([
  {
    id: 1,
    checkObject: 'GXXS0110',
    checkField: 'XXDZ',
    checkRule: '检测不唯一'
  },
  {
    id: 2,
    checkObject: 'GXXS0101',
    checkField: 'XXDM',
    checkRule: '检测不唯一'
  }
])

// 分页相关
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(100)

// 选中行
const selectedRows = ref([])

// 对话框相关
const dialogVisible = ref(false)
const dialogType = ref<'add' | 'edit'>('add')
const debugDialogVisible = ref(false)
const debugRule = ref('')
const debugResult = ref('')

// 表单相关
const formRef = ref<FormInstance>()
const formData = reactive({
  ruleTemplate: '',
  checkRange: '',
  checkFields: [
    {
      id: 63,
      fieldName: 'XXDM',
      fieldDesc: '学校代码',
      description: '学校代码'
    },
    {
      id: 64,
      fieldName: 'XXMC',
      fieldDesc: '学校名称',
      description: '学校名称'
    }
  ]
})

// 表单校验规则
const formRules: FormRules = {
  ruleTemplate: [{ required: true, message: '请选择规则模板', trigger: 'change' }],
  checkRange: [{ required: true, message: '请输入检测数据范围', trigger: 'blur' }]
}

// 处理树节点点击
const handleNodeClick = (data: any) => {
  console.log(data)
  // TODO: 加载该节点下的规则列表
}

// 处理表格选择
const handleSelectionChange = (rows: any[]) => {
  selectedRows.value = rows
}

// 处理分页
const handleSizeChange = (val: number) => {
  pageSize.value = val
  // TODO: 重新加载数据
}

const handleCurrentChange = (val: number) => {
  currentPage.value = val
  // TODO: 重新加载数据
}

// 查询
const handleSearch = () => {
  loading.value = true
  // TODO: 调用查询接口
  setTimeout(() => {
    loading.value = false
  }, 500)
}

// 添加规则
const handleAdd = () => {
  dialogType.value = 'add'
  dialogVisible.value = true
  // 重置表单
  Object.assign(formData, {
    ruleTemplate: '',
    checkRange: '',
    checkFields: []
  })
}

// 编辑规则
const handleEdit = (row: any) => {
  dialogType.value = 'edit'
  dialogVisible.value = true
  // 填充表单数据
  Object.assign(formData, row)
}

// 删除规则
const handleDelete = (row: any) => {
  ElMessageBox.confirm('此操作将永久删除该规则, 是否继续?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // TODO: 调用删除接口
    ElMessage.success('删除成功')
  })
}

// 批量删除
const handleBatchDelete = () => {
  if (!selectedRows.value.length) {
    ElMessage.warning('请选择要删除的项')
    return
  }
  ElMessageBox.confirm('此操作将永久删除选中的规则, 是否继续?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // TODO: 调用批量删除接口
    ElMessage.success('删除成功')
  })
}

// 调试规则
const handleDebug = (row: any) => {
  debugDialogVisible.value = true
  debugRule.value = row.checkRule
  debugResult.value = ''
}

// 执行调试
const runDebug = () => {
  loading.value = true
  // TODO: 调用调试接口
  setTimeout(() => {
    debugResult.value = '调试成功,未发现异常'
    loading.value = false
  }, 1000)
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate((valid) => {
    if (valid) {
      // TODO: 调用保存接口
      ElMessage.success(dialogType.value === 'add' ? '添加成功' : '修改成功')
      dialogVisible.value = false
      // 重新加载数据
    }
  })
}
</script>

<style scoped>
.quality-config {
  height: calc(100vh - 100px);
  
  .dialog-footer {
    @apply flex justify-end gap-2;
  }
}
</style> 